#include "EditorCore/Visitors/EntityUnderPositionFinder.h"
#include "EditorCore/Traversers/ChildrenFirstEntityTraverser.h"

using namespace cmn;

namespace editor_core {

	EntityUnderPositionFinder::EntityUnderPositionFinder( const Vec2& position ) :
		m_position( position ),
		m_entityIsFound( false ),
		m_foundEntity( 0 )
	{}

	EntityUnderPositionFinder::~EntityUnderPositionFinder()
	{}

	void EntityUnderPositionFinder::VisitEntity( IEntity* entity ) {
		if( m_entityIsFound )
			return;

		if( entity->Contains( m_position ) ) {
			m_entityIsFound = true;
			m_foundEntity = entity;
		}
		return;
	}

	IEntity* EntityUnderPositionFinder::FindEntityUnderCursor( IEntity* root, const Vec2& position ) {
		EntityTraverser* traverser = new ChildrenFirstEntityTraverser();
		EntityUnderPositionFinder* finder = new EntityUnderPositionFinder( position );

		traverser->Traverse( root, finder );

		IEntity* foundEntity = finder->GetFoundEntity();

		delete finder;
		delete traverser;

		return foundEntity;
	}

}
